// 使用远程Redis服务器的测试

import { RedisToolkit } from '../src';
import * as dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

async function remoteTest() {
  console.log('🌐 开始远程Redis服务器测试...\n');

  // 从环境变量获取Redis配置
  const redisHost = process.env['REDIS_HOST'] || 'localhost';
  const redisPort = parseInt(process.env['REDIS_PORT'] || '6379');

  console.log(`📡 连接到Redis服务器: ${redisHost}:${redisPort}`);

  // 创建Redis Toolkit实例
  const redis = new RedisToolkit({
    host: redisHost,
    port: redisPort,
    autoSerialize: true,
    // 可以添加密码等其他配置
    // password: process.env.REDIS_PASSWORD,
    // db: parseInt(process.env.REDIS_DB || '0'),
  });

  try {
    // 连接Redis
    console.log('🔌 正在连接Redis...');
    await redis.connect();
    console.log('✅ Redis连接成功\n');

    // 测试基础连接
    console.log('🏥 执行健康检查...');
    const health = await redis.healthCheck();
    console.log('健康状态:', health.status);
    console.log('连接信息:', health.connections);
    console.log('✅ 健康检查通过\n');

    // 测试缓存功能
    console.log('🗄️ 测试缓存功能...');
    const testData = {
      message: 'Hello from remote Redis!',
      timestamp: new Date().toISOString(),
      server: `${redisHost}:${redisPort}`
    };
    
    await redis.cache.set('remote-test', testData, { ttl: 300 });
    const cachedData = await redis.cache.get('remote-test');
    console.log('缓存数据:', cachedData);
    console.log('✅ 缓存功能正常\n');

    // 测试计数器功能
    console.log('🔢 测试计数器功能...');
    const counterKey = `remote-counter-${Date.now()}`;
    await redis.counter.increment(counterKey, 10);
    const count = await redis.counter.get(counterKey);
    console.log(`计数器 ${counterKey}:`, count);
    console.log('✅ 计数器功能正常\n');

    // 测试排行榜功能
    console.log('🏆 测试排行榜功能...');
    const leaderboardName = `remote-leaderboard-${Date.now()}`;
    await redis.leaderboard.updateScore(leaderboardName, 'remote-player1', 1000);
    await redis.leaderboard.updateScore(leaderboardName, 'remote-player2', 1500);
    await redis.leaderboard.updateScore(leaderboardName, 'remote-player3', 800);
    
    const topPlayers = await redis.leaderboard.getTopN(leaderboardName, 3);
    console.log('排行榜前3名:', topPlayers);
    console.log('✅ 排行榜功能正常\n');

    // 测试限流功能
    console.log('⏱️ 测试限流功能...');
    const rateLimitKey = `remote-limit-${Date.now()}`;
    
    // 连续测试5次请求
    for (let i = 1; i <= 5; i++) {
      const result = await redis.rateLimit.checkFixedWindow(rateLimitKey, 3, 60);
      console.log(`请求 ${i}: 允许=${result.allowed}, 剩余=${result.remaining}`);
    }
    console.log('✅ 限流功能正常\n');

    // 测试分布式锁功能
    console.log('🔒 测试分布式锁功能...');
    const lockResource = `remote-resource-${Date.now()}`;
    
    const token = await redis.lock.acquire(lockResource, { ttl: 30 });
    if (token) {
      console.log('🔓 成功获取锁:', token.substring(0, 8) + '...');
      
      // 模拟一些工作
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const released = await redis.lock.release(lockResource, token);
      console.log('🔐 释放锁:', released ? '成功' : '失败');
    }
    console.log('✅ 分布式锁功能正常\n');

    // 测试队列功能
    console.log('📋 测试队列功能...');
    const queueName = `remote-queue-${Date.now()}`;
    
    const jobId = await redis.queue.addJob(queueName, {
      type: 'remote-test-job',
      payload: { 
        message: 'Remote job test',
        server: `${redisHost}:${redisPort}`,
        timestamp: new Date().toISOString()
      },
    });
    console.log('添加作业ID:', jobId);
    
    const job = await redis.queue.getJob(queueName);
    if (job) {
      console.log('获取作业类型:', job.type);
      console.log('作业负载:', job.payload);
      
      // 完成作业
      await redis.queue.completeJob(job.id, { 
        processed: true,
        completedAt: new Date().toISOString()
      });
      console.log('作业已完成');
    }
    console.log('✅ 队列功能正常\n');

    // 测试集合功能
    console.log('📦 测试集合功能...');
    const setName = `remote-set-${Date.now()}`;
    
    await redis.set.add(setName, 'item1', 'item2', 'item3', 'item4');
    const setSize = await redis.set.size(setName);
    const members = await redis.set.getMembers(setName);
    console.log(`集合大小: ${setSize}, 成员:`, members);
    
    // 测试有序集合
    const zsetName = `remote-zset-${Date.now()}`;
    await redis.set.addScored(zsetName, 100, 'score1');
    await redis.set.addScored(zsetName, 200, 'score2');
    await redis.set.addScored(zsetName, 150, 'score3');
    
    const topScores = await redis.set.getRange(zsetName, 0, -1, true, true);
    console.log('有序集合排序:', topScores);
    console.log('✅ 集合功能正常\n');

    // 获取统计信息
    console.log('📊 获取统计信息...');
    const stats = await redis.getStats();
    console.log('连接统计:', stats.connection);
    if (stats.cache) {
      console.log('缓存统计:', {
        hitRate: stats.cache.hitRate,
        totalKeys: stats.cache.totalKeys
      });
    }
    console.log('✅ 统计信息获取正常\n');

    // 清理测试数据
    console.log('🧹 清理测试数据...');
    await redis.cache.del('remote-test');
    await redis.counter.reset(counterKey);
    await redis.leaderboard.clear(leaderboardName);
    await redis.rateLimit.reset(rateLimitKey);
    await redis.set.clear(setName);
    await redis.set.clear(zsetName);
    await redis.queue.clear(queueName);
    console.log('✅ 清理完成\n');

    console.log('🎉 远程Redis服务器测试全部通过！');
    console.log(`📍 服务器: ${redisHost}:${redisPort}`);
    console.log('🚀 Redis Toolkit在远程环境下工作正常！');

  } catch (error) {
    console.error('❌ 远程测试失败:', error);
    
    if (error instanceof Error) {
      if (error.message.includes('ECONNREFUSED')) {
        console.error('💡 提示: 请检查Redis服务器是否运行，以及网络连接是否正常');
      } else if (error.message.includes('ENOTFOUND')) {
        console.error('💡 提示: 请检查Redis服务器地址是否正确');
      } else if (error.message.includes('AUTH')) {
        console.error('💡 提示: 请检查Redis密码配置');
      }
    }
  } finally {
    // 断开连接
    try {
      await redis.disconnect();
      console.log('📡 Redis连接已断开');
    } catch (error) {
      console.error('断开连接时出错:', error);
    }
  }
}

// 运行测试
if (require.main === module) {
  remoteTest().catch(console.error);
}

export { remoteTest };
